package top.yangbuyi.config.redis;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.nio.charset.Charset;


/**
 * @description: 杨不易网站:www.yangbuyi.top
 * @program: yangbuyiopenHis2020
 * @ClassName: StringRedisSerializer
 * @create: 2020-08-28 22:22
 * @author: yangbuyi
 * @since： JDK1.8
 * @StringRedisSerializer: aa$必须重写序列化器，否则@Cacheable注解的key会报类型转换错误
 **/
public class StringRedisSerializer implements RedisSerializer<Object> {

	  private final Charset charset;

	  private final String target = "\"";

	  private final String replacement = "";

	  public StringRedisSerializer() {
			this(Charset.forName("UTF8"));
	  }

	  public StringRedisSerializer(Charset charset) {
			Assert.notNull(charset, "Charset must not be null!");
			this.charset = charset;
	  }

	  @Override
	  public String deserialize(byte[] bytes) {
			return (bytes == null ? null : new String(bytes, charset));
	  }

	  @Override
	  public byte[] serialize(Object object) {
			String string = JSON.toJSONString(object);
			if (string == null) {
				  return null;
			}
			string = string.replace(target, replacement);
			return string.getBytes(charset);
	  }
}
